package BanyuanClub.Study.Day0310.生产者消费者模式;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TextCopy<T> {
    private Object[] arr;
    private int size;
    //创建一个锁
    private ReentrantLock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    //构造方法
    public TextCopy(int limiy){
        this.arr = new Object[limiy];
    }

    //往arr中放入对象
    public void put(T obj){
        lock.lock();
            try {
                //当数组已满时，生产者等待
        while (size == arr.length){
            System.out.println("队列已满，生产者等待中，释放锁");
                notFull.await();
        }
            arr[size++] = obj;
        notFull.signalAll();
                System.out.println("生产者放入一个对象");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

    }

    public synchronized T take() throws InterruptedException {
        lock.lock();
            try {
        while (size == 0){
            System.out.println("队列已空，消费者等待中，释放锁");
            notEmpty.await();
        }
        Object obj = arr[size--];
        arr[--size] = null;
                System.out.println("消费者取出一个对象");
        notFull.signalAll();
        return (T)obj;

            }finally {
                lock.unlock();
            }

    }

}
